import store from '@/store'
export default {
  config: {
    baseURL: 'https://luntan.xiaouyf.cn/apis',
    // 请求拦截器
    beforeRequest(options = {}) {
      return new Promise((resolve, reject) => {
        options.url = this.baseURL + options.url
        // 从本地存储获取 token
        const token = uni.getStorageSync('token')
        options.header = {
          Authorization: token ? JSON.parse(token) : ''
        }
        options.method = options.method || 'GET'
        resolve(options)
      })
    },
    // 响应拦截器
    handleResponse(res) {
      return new Promise((resolve, reject) => {
        // 默认错误消息
        const defaultMsg = '请求失败'
        if (process.env.NODE_ENV === 'development') {
        }
        // 检查 HTTP 状态码
        if (res.statusCode !== 200) {
          const msg = res.data?.msg || defaultMsg
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          return reject(new Error(msg)) // 用 Error 对象返回错误信息
        }

        // 检查业务逻辑状态码
        if (res.data.code === 500) {
          const msg = res.data.message || '系统异常'
          uni.showToast({
            title: msg,
            icon: 'none'
          })
          return reject(new Error(msg))
        }

        // 检查是否需要登录
        if (res.data.code === 401) {
          store.dispatch('loginOut')
          const msg = res.data.message || '登录已过期'
          uni.navigateTo({ url: '/pages/tabbar/getphone' })
          return reject(new Error(msg))
        }

        // 返回成功数据
        resolve(res.data)
      })
    }
  },
  request(options = {}) {
    return this.config
      .beforeRequest(options)
      .then((opt) => uni.request(opt))
      .then(this.config.handleResponse)
  },
  // GET请求
  get(url, params = null, options = {}) {
    options.url = url
    options.url += params
      ? '?' +
        Object.keys(params)
          .map((key) => key + '=' + params[key])
          .join('&')
      : ''
    options.method = 'GET'
    return this.request(options)
  },
  // POST请求
  post(url, data = {}, options = {}) {
    options.url = url
    options.method = 'POST'
    options.data = data
    return this.request(options)
  },
  // put 请求
  put(url, data = {}, options = {}) {
    options.url = url
    options.method = 'PUT'
    options.data = data
    return this.request(options)
  },
  // delete 请求
  delete(url, data = {}, options = {}) {
    options.url = url
    options.method = 'DELETE'
    options.data = data
    return this.request(options)
  }
}

export const runApi = async (api, data, final, option) => {
  return new Promise((resolve, reject) => {
    api(data, option)
      .then((res) => {
        resolve(res)
        final(res)
      })
      .catch((err) => {
        reject(err)
        final(err)
      })
  })
}
